# import tkinter as tk
# import time


# window=tk.Tk()
# window.title('66666')
# window.geometry('800x400')
# print("电脑的分辨率是%dx%d"%(window.winfo_screenwidth(),window.winfo_screenheight()))
# window.update()
# print("窗口的分辨率是%dx%d"%(window.winfo_width(),window.winfo_height()))
# #背景色
# window["background"]="#6A81C1"
# #最顶
# window.attributes('-topmost',True)
# #透明度
# window.attributes('-alpha',0.8)
# window.maxsize(1000,1000)
# window.minsize(50,50)



# text=tk.Label(window,text="c语言中文网，欢迎您",bg="black",fg="white",font=('times',20,'bold italic'))
# text.pack()

# button=tk.Button(window,text="关闭",command=window.quit)

# button.pack(side="bottom")

# def callback():
#     print("执行回调函数","yolo欢迎您")

# button= tk.Button(window,text="执行",command=callback)
# button.pack()


# #时间
# def gettime():
#     dstr.set(time.strftime("%H:%M:%S"))
#     window.after(1000,gettime)

# dstr=tk.StringVar()
# lb=tk.Label(window,textvariable=dstr,fg='green',font=("微软雅黑",100))
# lb.pack()
# gettime()

# window.mainloop()







# from cProfile import label
# import tkinter as tk
# win =tk.Tk()
# win.title("C语言中文网")
# win.geometry("400x400")
# label=tk.Label(win,text="网址:c.biancheng.net",font=('宋体',20,'bold italic'),bg="#7ccd7c",
#                width=30,height=5,
#                padx=10,pady=5,borderwidth=10,relief="sunken")
# label.pack()
# win.mainloop()








# import tkinter as tk
# from tkinter import messagebox

# window=tk.Tk()
# window.title("你好")
# window.geometry('400x300+300+200')

# def click_button():
#     messagebox.showinfo(title='温馨提示',message='欢迎使用')

# button=tk.Button(window,text='点击前往',bg='#824682',width=20,height=5,command=click_button).pack()

# window.mainloop()








# import tkinter as tk
# from tkinter import messagebox
# win =tk.Tk()
# win.title('欢迎')
# win.geometry('400x200+100+100')
# win.resizable(0,0)

# tk.Label(win,text='账号：').grid(row=0)
# tk.Label(win,text='密码：').grid(row=1)
# e1=tk.Entry(win)

# #以***的形式代替密码
# e2=tk.Entry(win,show='*')

# e1.grid(row=0,column=1,padx=10,pady=5)
# e2.grid(row=1,column=1,padx=10,pady=5)

# def login():
#     messagebox.showinfo('欢迎您到来')

# tk.Button(win,text="登录",width=10,
#           command=login).grid(row=5,column=0,sticky="w",padx=10,pady=5)

# win.mainloop()








# import tkinter as tk
# from tkinter import messagebox
# win=tk.Tk()

# win.geometry('400x400+200+200')
# win.title=('登录')
# win.resizable(0,0)



# def check():
#     if entry1.get()=='C语言中文网':
#         messagebox.showinfo('输入正确')
#         return True
#     else:
#         messagebox.showinfo('输入错误')
#         entry1.delete(0,tk.END)
#         return False

# label1=tk.Label(win,text='账号：')
# label2=tk.Label(win,text='密码：')
# label1.grid(row=0)
# label2.grid(row=1)

# Dy_String=tk.StringVar()

# entry1=tk.Entry(win,textvariable=Dy_String,validate='focusout',validatecommand=check)
# entry2=tk.Entry(win)

# entry1.grid(row=0,column=1)
# entry2.grid(row=1,column=1)

# win.mainloop()






# import tkinter as tk
# from tkinter import messagebox
# import re  # 导入正则表达式模块

# win = tk.Tk()
# win.geometry('400x200+200+200')
# win.title('登录验证')  # 修正title设置方式
# win.resizable(0, 0)

# def validate_account():
#     """验证账号：必须全部由数字组成"""
#     account = entry1.get()
#     if account and account.isdigit():  # 检查是否全部为数字
#         return True
#     else:
#         messagebox.showerror('输入错误', '账号必须由数字组成！')
#         entry1.delete(0, tk.END)
#         return False

# def validate_password():
#     """验证密码：必须包含数字、字母和符号"""
#     password = entry2.get()
#     if password:
#         # 使用正则表达式检查密码复杂度
#         has_digit = re.search(r'\d', password) is not None      # 包含数字
#         has_letter = re.search(r'[a-zA-Z]', password) is not None  # 包含字母
#         has_symbol = re.search(r'[^\w\s]', password) is not None   # 包含符号
        
#         if has_digit and has_letter and has_symbol:
#             return True
#         else:
#             messagebox.showerror('输入错误', '密码必须包含数字、字母和符号！')
#             entry2.delete(0, tk.END)
#             return False
#     return False

# def check_login():
#     """检查登录信息"""
#     if validate_account() and validate_password():
#         messagebox.showinfo('登录成功', '欢迎登录！')
#         return True
#     return False

# # 创建标签
# label1 = tk.Label(win, text='账号：')
# label2 = tk.Label(win, text='密码：')
# label1.grid(row=0, column=0, padx=10, pady=10, sticky='e')
# label2.grid(row=1, column=0, padx=10, pady=10, sticky='e')

# # 创建输入框
# Dy_String1=tk.StringVar()
# Dy_String2=tk.StringVar()
# entry1 = tk.Entry(win, width=20,textvariable=Dy_String1,validate='focusout',validatecommand=validate_account)
# entry2 = tk.Entry(win, width=20, show='*',textvariable=Dy_String2,validate='focusout',validatecommand=validate_password)  # 密码显示为星号

# entry1.grid(row=0, column=1, padx=10, pady=10)
# entry2.grid(row=1, column=1, padx=10, pady=10)

# # 创建登录按钮
# login_button = tk.Button(win, text='登录', command=check_login, width=10)
# login_button.grid(row=2, column=1, padx=10, pady=20, sticky='w')

# win.mainloop()




# from tkinter import *
# win=Tk()
# win.title('yolo')
# win.geometry('800x800')

# w=Spinbox(win,from_=0,to=20,increment=2,width=30,bg="#BB1E1E")
# w.grid()

# strings=Spinbox(win,values=('Python','java','C语言','PHP'))
# strings.grid()

# text = Text(win, width=50, height=30, undo=True, autoseparators=False)
# text.grid()
# text.insert(INSERT, 'C语言中文网,一个有温度的网站')

# # 适用 pack(fill=X) 可以设置文本域的填充模式。比如 X表示沿水平方向填充，Y表示沿垂直方向填充，BOTH表示沿水平、垂直方向填充
# def backout():
#     text.edit_undo()
# def regain():
#     text.edit_redo()
# Button(win,text = '撤销',command = backout).grid(row=20, column=0, sticky="w", padx=10, pady=5)
# Button(win,text = '恢复',command = regain).grid(row=20, column=0, sticky="e", padx=10, pady=5)

# # INSERT 光标处插入；END 末尾处插入

# win.mainloop()








# from tkinter import *
# import tkinter.messagebox
# win=Tk()
# win.title('yolo')
# win.geometry('800x800')
# def menuCommand():
#     tkinter.messagebox.showinfo('主菜单栏','你正在使用主菜单栏')
# main_menu=Menu(win)

# main_menu.add_command(label="文件",command=menuCommand)
# main_menu.add_command(label="编辑",command=menuCommand)
# main_menu.add_command(label="格式",command=menuCommand)
# main_menu.add_command(label="查看",command=menuCommand)
# main_menu.add_command(label="帮助",command=menuCommand)
# win.config (menu=main_menu)

# win.mainloop()







# import tkinter as tk
# win=tk.Tk()
# win.config(bg='#888888')
# win.title('yolo')
# win.geometry('400x300')
# def func():
#     print('您通过弹出菜单执行了命令')

# menu=tk.Menu(win,tearoff=False)
# menu.add_command(label="新建",command=func)
# menu.add_command(label="复制",command=func)
# menu.add_command(label="粘贴",command=func)
# menu.add_command(label="新建",command=func)

# def command(event):
#    menu.post(event.x_root,event.y_root)

# win.bind('<Button-3>',command)

# win.mainloop()







# from tkinter import *
# import tkinter as tk
# import tkinter.messagebox


# def configure_window(window):
#     window.config(bg="#07FAF6")
#     window.title('yolo')
#     window.geometry('400x300')
    

# win = Tk()
# configure_window(win) 


# def New_win(event=None):
#     win = tk.Toplevel()
#     configure_window(win)
#     mainmenu=Menu(win)

#     filemenu=Menu(mainmenu,tearoff=False)


#     filemenu.add_command(label='新建',command=New_win,accelerator="Ctrl+N")
#     filemenu.add_command(label='打开',command=New_win,accelerator="Ctrl+O")
#     filemenu.add_command(label='保存',command=New_win,accelerator="Ctrl+S")

#     filemenu.add_separator()
#     filemenu.add_command(label='退出',command=win.quit)

#     mainmenu.add_cascade(label='文件',menu=filemenu)

#     win.config(menu=mainmenu)
#     win.bind('<Control-n>',New_win)
#     win.bind('<Control-N>',New_win)
#     win.bind('<Control-o>',New_win)
#     win.bind('<Control-O>',New_win)
#     win.bind('<Control-s>',New_win)
#     win.bind('<Control-S>',New_win)
#     win.focus_set()
 
    
# def Open_file():
#     open

# mainmenu=Menu(win)

# filemenu=Menu(mainmenu,tearoff=False)


# filemenu.add_command(label='新建',command=New_win,accelerator="Ctrl+N")
# filemenu.add_command(label='打开',command=New_win,accelerator="Ctrl+O")
# filemenu.add_command(label='保存',command=New_win,accelerator="Ctrl+S")

# filemenu.add_separator()
# filemenu.add_command(label='退出',command=win.quit)

# mainmenu.add_cascade(label='文件',menu=filemenu)

# win.config(menu=mainmenu)
# win.bind('<Control-n>',New_win)
# win.bind('<Control-N>',New_win)
# win.bind('<Control-o>',New_win)
# win.bind('<Control-O>',New_win)
# win.bind('<Control-s>',New_win)
# win.bind('<Control-S>',New_win)



# win.mainloop()







# import tkinter as tk
# win=tk.Tk()
# win.geometry('300x200')


# frame1=tk.Frame(win)
# frame1.pack()


# frame_left=tk.Frame(frame1)
# tk.Label(frame_left,text='左边标签1',bg='#888888',width=10,height=5).grid(row=0,column=0)
# tk.Label(frame_left,text='左边标签2',bg="#D65E5E",width=10,height=5).grid(row=1,column=1)
# frame_left.pack(side=tk.LEFT)


# frame_right=tk.Frame(frame1)
# tk.Label(frame_right,text='右边标签1',bg="#3FE368",width=10,height=5).grid(row=0,column=1)
# tk.Label(frame_right,text='右边标签2',bg="#BA47D9",width=10,height=5).grid(row=1,column=0)
# tk.Label(frame_right,text='右边标签3',bg="#D12994",width=10,height=5).grid(row=1,column=1)
# frame_right.pack(side=tk.RIGHT)


# win.mainloop()







# from tkinter import *
# win=Tk()
# win.config(bg='#666666')
# win.geometry('500x500')

# for i in range(36):
#     for j in range(36):
#         Button (win, text="("+str(i)+","+str(j)+")",bg='#555555',width=3,height=1).grid(row=i,column=j)


# Label(win,text='yolo',fg='#285476',font=('楷体',12,'bold')).grid(row=4,column=11)


# win.mainloop()





















# import tkinter as tk
# from tkinter import filedialog, messagebox, scrolledtext
# import os
# from datetime import datetime

# class BasicNotepad:
#     def __init__(self, root):
#         self.root = root
#         self.root.title("简易记事本 - 未命名")
#         self.root.geometry("800x600")
        
#         self.current_file = None  # 当前文件路径
#         self.is_modified = False  # 文件是否修改未保存
#         self.recent_files = []    # 最近打开的文件列表
#         self.max_recent = 5       # 最大最近文件数量
        
#         self.setup_ui()
#         self.setup_bindings()
        
#     def setup_ui(self):
#         """设置用户界面"""
#         # 创建菜单栏
#         menubar = tk.Menu(self.root)
#         self.root.config(menu=menubar)
        
#         # 文件菜单
#         file_menu = tk.Menu(menubar, tearoff=0)
#         menubar.add_cascade(label="文件", menu=file_menu)
        
#         file_menu.add_command(label="新建", command=self.new_file, accelerator="Ctrl+N")
#         file_menu.add_command(label="打开", command=self.open_file, accelerator="Ctrl+O")
#         file_menu.add_separator()
#         file_menu.add_command(label="保存", command=self.save_file, accelerator="Ctrl+S")
#         file_menu.add_command(label="另存为", command=self.save_as_file, accelerator="Ctrl+Shift+S")
#         file_menu.add_separator()
#         file_menu.add_command(label="退出", command=self.exit_app, accelerator="Ctrl+Q")
        
#         # 最近文件子菜单
#         self.recent_menu = tk.Menu(file_menu, tearoff=0)
#         file_menu.add_cascade(label="最近文件", menu=self.recent_menu)
#         self.update_recent_menu()
        
#         # 模板菜单
#         template_menu = tk.Menu(menubar, tearoff=0)
#         menubar.add_cascade(label="模板", menu=template_menu)
#         template_menu.add_command(label="空白笔记", command=lambda: self.new_from_template("blank"))
#         template_menu.add_command(label="待办清单", command=lambda: self.new_from_template("todo"))
#         template_menu.add_command(label="日记模板", command=lambda: self.new_from_template("diary"))
        
#         # 主文本区域
#         self.text_area = scrolledtext.ScrolledText(
#             self.root, 
#             wrap=tk.WORD, 
#             font=("Consolas", 12),
#             undo=True  # 启用撤销功能
#         )
#         self.text_area.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
        
#         # 状态栏
#         self.status_bar = tk.Label(self.root, text="就绪", relief=tk.SUNKEN, anchor=tk.W)
#         self.status_bar.pack(side=tk.BOTTOM, fill=tk.X)
        
#         # 绑定文本修改事件
#         self.text_area.bind("<<Modified>>", self.on_text_modified)
        
#     def setup_bindings(self):
#         """设置快捷键绑定"""
#         self.root.bind("<Control-n>", lambda e: self.new_file())
#         self.root.bind("<Control-N>", lambda e: self.new_file())
#         self.root.bind("<Control-o>", lambda e: self.open_file())
#         self.root.bind("<Control-O>", lambda e: self.open_file())
#         self.root.bind("<Control-s>", lambda e: self.save_file())
#         self.root.bind("<Control-S>", lambda e: self.save_file())
#         self.root.bind("<Control-Shift-S>", lambda e: self.save_as_file())
#         self.root.bind("<Control-Shift-s>", lambda e: self.save_as_file())
#         self.root.bind("<Control-q>", lambda e: self.exit_app())
#         self.root.bind("<Control-Q>", lambda e: self.exit_app())
    
#     def on_text_modified(self, event):
#         """文本修改事件处理"""
#         if self.text_area.edit_modified():
#             self.is_modified = True
#             self.update_title()
#             self.text_area.edit_modified(False)  # 重置修改标志
    
#     def update_title(self):
#         """更新窗口标题"""
#         filename = os.path.basename(self.current_file) if self.current_file else "未命名"
#         modified = "*" if self.is_modified else ""
#         self.root.title(f"简易记事本 - {filename}{modified}")
    
#     def update_status(self, message):
#         """更新状态栏"""
#         self.status_bar.config(text=message)
    
#     def new_file(self):
#         """新建文件"""
#         if self.check_save():
#             self.text_area.delete(1.0, tk.END)
#             self.current_file = None
#             self.is_modified = False
#             self.update_title()
#             self.update_status("新建文件")
    
#     def new_from_template(self, template_type):
#         """从模板新建"""
#         if self.check_save():
#             self.text_area.delete(1.0, tk.END)
            
#             templates = {
#                 "blank": "",
#                 "todo": "# 待办清单\n\n- [ ] 任务1\n- [ ] 任务2\n- [ ] 任务3\n",
#                 "diary": f"# {datetime.now().strftime('%Y年%m月%d日')}\n\n天气：\n心情：\n\n## 今日总结：\n\n"
#             }
            
#             self.text_area.insert(1.0, templates.get(template_type, ""))
#             self.current_file = None
#             self.is_modified = True
#             self.update_title()
#             self.update_status(f"已创建{template_type}模板")
    
#     def open_file(self, filepath=None):
#         """打开文件"""
#         if self.check_save():
#             if not filepath:
#                 file_types = [
#                     ("文本文件", "*.txt"),
#                     ("Markdown文件", "*.md"),
#                     ("HTML文件", "*.html"),
#                     ("Python文件", "*.py"),
#                     ("所有文件", "*.*")
#                 ]
#                 filepath = filedialog.askopenfilename(filetypes=file_types)
            
#             if filepath:
#                 try:
#                     with open(filepath, 'r', encoding='utf-8') as file:
#                         content = file.read()
                    
#                     self.text_area.delete(1.0, tk.END)
#                     self.text_area.insert(1.0, content)
#                     self.current_file = filepath
#                     self.is_modified = False
#                     self.update_title()
#                     self.add_to_recent(filepath)
#                     self.update_status(f"已打开: {os.path.basename(filepath)}")
                    
#                 except Exception as e:
#                     messagebox.showerror("错误", f"无法打开文件:\n{str(e)}")
    
#     def save_file(self):
#         """保存文件"""
#         if self.current_file:
#             try:
#                 content = self.text_area.get(1.0, tk.END)
#                 with open(self.current_file, 'w', encoding='utf-8') as file:
#                     file.write(content)
                
#                 self.is_modified = False
#                 self.update_title()
#                 self.update_status(f"已保存: {os.path.basename(self.current_file)}")
#                 return True
                
#             except Exception as e:
#                 messagebox.showerror("错误", f"保存失败:\n{str(e)}")
#                 return False
#         else:
#             return self.save_as_file()
    
#     def save_as_file(self):
#         """另存为文件"""
#         file_types = [
#             ("文本文件", "*.txt"),
#             ("Markdown文件", "*.md"),
#             ("HTML文件", "*.html"),
#             ("Python文件", "*.py"),
#             ("所有文件", "*.*")
#         ]
        
#         filepath = filedialog.asksaveasfilename(
#             defaultextension=".txt",
#             filetypes=file_types
#         )
        
#         if filepath:
#             try:
#                 content = self.text_area.get(1.0, tk.END)
#                 with open(filepath, 'w', encoding='utf-8') as file:
#                     file.write(content)
                
#                 self.current_file = filepath
#                 self.is_modified = False
#                 self.update_title()
#                 self.add_to_recent(filepath)
#                 self.update_status(f"已另存为: {os.path.basename(filepath)}")
#                 return True
                
#             except Exception as e:
#                 messagebox.showerror("错误", f"保存失败:\n{str(e)}")
#                 return False
#         return False
    
#     def check_save(self):
#         """检查是否需要保存"""
#         if self.is_modified:
#             result = messagebox.askyesnocancel(
#                 "保存更改",
#                 "文件已修改，是否保存更改？"
#             )
            
#             if result is None:  # 取消
#                 return False
#             elif result:  # 是
#                 return self.save_file()
#             else:  # 否
#                 return True
#         return True
    
#     def exit_app(self):
#         """退出应用"""
#         if self.check_save():
#             self.root.quit()
    
#     def add_to_recent(self, filepath):
#         """添加到最近文件列表"""
#         if filepath in self.recent_files:
#             self.recent_files.remove(filepath)
#         self.recent_files.insert(0, filepath)
#         self.recent_files = self.recent_files[:self.max_recent]
#         self.update_recent_menu()
    
#     def update_recent_menu(self):
#         """更新最近文件菜单"""
#         self.recent_menu.delete(0, tk.END)
#         for filepath in self.recent_files:
#             if os.path.exists(filepath):
#                 filename = os.path.basename(filepath)
#                 self.recent_menu.add_command(
#                     label=filename,
#                     command=lambda f=filepath: self.open_file(f)
#                 )
#         if not self.recent_files:
#             self.recent_menu.add_command(label="无最近文件", state=tk.DISABLED)

# # 启动应用
# if __name__ == "__main__":
#     root = tk.Tk()
#     app = BasicNotepad(root)
#     root.mainloop()

































import tkinter as tk
from tkinter import filedialog, messagebox, scrolledtext, simpledialog, colorchooser
import os
from datetime import datetime
import re

class EnhancedNotepad:
    def __init__(self, root):
        self.root = root
        self.root.title("增强记事本 - 未命名")
        self.root.geometry("800x600")
        
        self.current_file = None  # 当前文件路径
        self.is_modified = False  # 文件是否修改未保存
        self.recent_files = []    # 最近打开的文件列表
        self.max_recent = 5       # 最大最近文件数量
        self.clipboard_history = []  # 剪贴板历史
        self.max_clipboard_history = 10  # 最大剪贴板历史数量
        self.find_dialog = None  # 查找对话框
        self.replace_dialog = None  # 替换对话框
        
        self.setup_ui()
        self.setup_bindings()
        
    def setup_ui(self):
        """设置用户界面"""
        # 创建菜单栏
        menubar = tk.Menu(self.root)
        self.root.config(menu=menubar)
        
        # 文件菜单
        file_menu = tk.Menu(menubar, tearoff=0)
        menubar.add_cascade(label="文件", menu=file_menu)
        
        file_menu.add_command(label="新建", command=self.new_file_with_template, accelerator="Ctrl+N")
        file_menu.add_command(label="打开", command=self.open_file, accelerator="Ctrl+O")
        file_menu.add_separator()
        file_menu.add_command(label="保存", command=self.save_file, accelerator="Ctrl+S")
        file_menu.add_command(label="另存为", command=self.save_as_file, accelerator="Ctrl+Shift+S")
        file_menu.add_separator()
        file_menu.add_command(label="退出", command=self.exit_app, accelerator="Ctrl+Q")
        
        # 最近文件子菜单
        self.recent_menu = tk.Menu(file_menu, tearoff=0)
        file_menu.add_cascade(label="最近文件", menu=self.recent_menu)
        self.update_recent_menu()
        
        # 编辑菜单
        edit_menu = tk.Menu(menubar, tearoff=0)
        menubar.add_cascade(label="编辑", menu=edit_menu)
        
        edit_menu.add_command(label="撤销", command=self.undo, accelerator="Ctrl+Z")
        edit_menu.add_command(label="重做", command=self.redo, accelerator="Ctrl+Y")
        edit_menu.add_separator()
        edit_menu.add_command(label="剪切", command=self.cut, accelerator="Ctrl+X")
        edit_menu.add_command(label="复制", command=self.copy, accelerator="Ctrl+C")
        edit_menu.add_command(label="粘贴", command=self.paste, accelerator="Ctrl+V")
        edit_menu.add_command(label="粘贴历史", command=self.show_clipboard_history)
        edit_menu.add_separator()
        edit_menu.add_command(label="全选", command=self.select_all, accelerator="Ctrl+A")
        edit_menu.add_command(label="列选模式", command=self.toggle_column_select)
        
        # 查找菜单
        find_menu = tk.Menu(menubar, tearoff=0)
        menubar.add_cascade(label="查找", menu=find_menu)
        
        find_menu.add_command(label="查找", command=self.show_find_dialog, accelerator="Ctrl+F")
        find_menu.add_command(label="替换", command=self.show_replace_dialog, accelerator="Ctrl+H")
        
        # 格式菜单
        format_menu = tk.Menu(menubar, tearoff=0)
        menubar.add_cascade(label="格式", menu=format_menu)
        
        format_menu.add_command(label="粗体", command=lambda: self.apply_format("bold"), accelerator="Ctrl+B")
        format_menu.add_command(label="斜体", command=lambda: self.apply_format("italic"), accelerator="Ctrl+I")
        format_menu.add_command(label="下划线", command=lambda: self.apply_format("underline"), accelerator="Ctrl+U")
        format_menu.add_command(label="删除线", command=lambda: self.apply_format("strike"))
        format_menu.add_separator()
        format_menu.add_command(label="字体", command=self.choose_font)
        format_menu.add_command(label="颜色", command=self.choose_color)
        
        # 主文本区域
        self.text_area = scrolledtext.ScrolledText(
            self.root, 
            wrap=tk.WORD, 
            font=("Consolas", 12),
            undo=True,  # 启用撤销功能
            maxundo=100  # 设置最大撤销步数
        )
        self.text_area.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
        
        # 状态栏
        self.status_bar = tk.Label(self.root, text="就绪", relief=tk.SUNKEN, anchor=tk.W)
        self.status_bar.pack(side=tk.BOTTOM, fill=tk.X)
        
        # 绑定文本修改事件
        self.text_area.bind("<<Modified>>", self.on_text_modified)
        
        # 工具栏框架
        self.toolbar_frame = tk.Frame(self.root)
        self.toolbar_frame.pack(fill=tk.X)
        
        # 添加格式按钮到工具栏
        bold_btn = tk.Button(self.toolbar_frame, text="粗体", command=lambda: self.apply_format("bold"))
        bold_btn.pack(side=tk.LEFT, padx=2, pady=2)
        
        italic_btn = tk.Button(self.toolbar_frame, text="斜体", command=lambda: self.apply_format("italic"))
        italic_btn.pack(side=tk.LEFT, padx=2, pady=2)
        
        underline_btn = tk.Button(self.toolbar_frame, text="下划线", command=lambda: self.apply_format("underline"))
        underline_btn.pack(side=tk.LEFT, padx=2, pady=2)
        
        strike_btn = tk.Button(self.toolbar_frame, text="删除线", command=lambda: self.apply_format("strike"))
        strike_btn.pack(side=tk.LEFT, padx=2, pady=2)
        
        font_btn = tk.Button(self.toolbar_frame, text="字体", command=self.choose_font)
        font_btn.pack(side=tk.LEFT, padx=2, pady=2)
        
        color_btn = tk.Button(self.toolbar_frame, text="颜色", command=self.choose_color)
        color_btn.pack(side=tk.LEFT, padx=2, pady=2)
        
        # 列选模式状态
        self.column_select_mode = False
        
    def setup_bindings(self):
        """设置快捷键绑定"""
        self.root.bind("<Control-n>", lambda e: self.new_file_with_template())
        self.root.bind("<Control-N>", lambda e: self.new_file_with_template())
        self.root.bind("<Control-o>", lambda e: self.open_file())
        self.root.bind("<Control-O>", lambda e: self.open_file())
        self.root.bind("<Control-s>", lambda e: self.save_file())
        self.root.bind("<Control-S>", lambda e: self.save_file())
        self.root.bind("<Control-Shift-S>", lambda e: self.save_as_file())
        self.root.bind("<Control-Shift-s>", lambda e: self.save_as_file())
        self.root.bind("<Control-q>", lambda e: self.exit_app())
        self.root.bind("<Control-Q>", lambda e: self.exit_app())
        self.root.bind("<Control-f>", lambda e: self.show_find_dialog())
        self.root.bind("<Control-F>", lambda e: self.show_find_dialog())
        self.root.bind("<Control-h>", lambda e: self.show_replace_dialog())
        self.root.bind("<Control-H>", lambda e: self.show_replace_dialog())
        self.root.bind("<Control-b>", lambda e: self.apply_format("bold"))
        self.root.bind("<Control-B>", lambda e: self.apply_format("bold"))
        self.root.bind("<Control-i>", lambda e: self.apply_format("italic"))
        self.root.bind("<Control-I>", lambda e: self.apply_format("italic"))
        self.root.bind("<Control-u>", lambda e: self.apply_format("underline"))
        self.root.bind("<Control-U>", lambda e: self.apply_format("underline"))
        
        # 绑定鼠标事件用于列选模式
        self.text_area.bind("<ButtonPress-1>", self.on_mouse_press)
        self.text_area.bind("<B1-Motion>", self.on_mouse_drag)
        self.text_area.bind("<ButtonRelease-1>", self.on_mouse_release)
    
    def on_mouse_press(self, event):
        """鼠标按下事件处理"""
        if self.column_select_mode:
            self.column_select_start = (event.x, event.y)
            return "break"  # 阻止默认选择行为
        return None
    
    def on_mouse_drag(self, event):
        """鼠标拖动事件处理"""
        if self.column_select_mode:
            # 在列选模式下，绘制选择矩形
            self.text_area.delete("select_rect")
            x0, y0 = self.column_select_start
            x1, y1 = event.x, event.y
            self.text_area.create_rectangle(x0, y0, x1, y1, outline="blue", tag="select_rect")
            return "break"  # 阻止默认选择行为
        return None
    
    def on_mouse_release(self, event):
        """鼠标释放事件处理"""
        if self.column_select_mode:
            # 在列选模式下，处理列选择
            self.text_area.delete("select_rect")
            x0, y0 = self.column_select_start
            x1, y1 = event.x, event.y
            
            # 获取选择的起始和结束位置
            start_index = self.text_area.index(f"@{x0},{y0}")
            end_index = self.text_area.index(f"@{x1},{y1}")
            
            # 清除现有选择
            self.text_area.tag_remove("sel", "1.0", tk.END)
            
            # 选择矩形区域内的文本
            start_line, start_col = map(int, start_index.split('.'))
            end_line, end_col = map(int, end_index.split('.'))
            
            # 确保起始列小于结束列
            if start_col > end_col:
                start_col, end_col = end_col, start_col
            
            # 选择矩形区域
            for line in range(min(start_line, end_line), max(start_line, end_line) + 1):
                line_start = f"{line}.{start_col}"
                line_end = f"{line}.{end_col}"
                self.text_area.tag_add("sel", line_start, line_end)
            
            return "break"  # 阻止默认选择行为
        return None
    
    def on_text_modified(self, event):
        """文本修改事件处理"""
        if self.text_area.edit_modified():
            self.is_modified = True
            self.update_title()
            self.text_area.edit_modified(False)  # 重置修改标志
    
    def update_title(self):
        """更新窗口标题"""
        filename = os.path.basename(self.current_file) if self.current_file else "未命名"
        modified = "*" if self.is_modified else ""
        self.root.title(f"增强记事本 - {filename}{modified}")
    
    def update_status(self, message):
        """更新状态栏"""
        self.status_bar.config(text=message)
    
    def new_file_with_template(self):
        """新建文件时选择模板"""
        if self.check_save():
            # 创建模板选择对话框
            template_dialog = tk.Toplevel(self.root)
            template_dialog.title("选择模板")
            template_dialog.geometry("300x200")
            template_dialog.transient(self.root)
            template_dialog.grab_set()
            
            # 居中对话框
            template_dialog.update_idletasks()
            x = self.root.winfo_x() + (self.root.winfo_width() - template_dialog.winfo_width()) // 2
            y = self.root.winfo_y() + (self.root.winfo_height() - template_dialog.winfo_height()) // 2
            template_dialog.geometry(f"+{x}+{y}")
            
            # 添加模板选择标签
            label = tk.Label(template_dialog, text="请选择模板类型:")
            label.pack(pady=10)
            
            # 模板选择框架
            frame = tk.Frame(template_dialog)
            frame.pack(pady=10)
            
            # 模板选项
            templates = {
                "blank": "空白笔记",
                "todo": "待办清单",
                "diary": "日记模板",
                "code": "代码模板"
            }
            
            selected_template = tk.StringVar(value="blank")
            
            for key, value in templates.items():
                rb = tk.Radiobutton(frame, text=value, variable=selected_template, value=key)
                rb.pack(anchor=tk.W, padx=20, pady=5)
            
            # 确认按钮
            def confirm_template():
                template_dialog.destroy()
                self.new_from_template(selected_template.get())
            
            confirm_btn = tk.Button(template_dialog, text="确认", command=confirm_template)
            confirm_btn.pack(pady=10)
            
            # 取消按钮
            cancel_btn = tk.Button(template_dialog, text="取消", command=template_dialog.destroy)
            cancel_btn.pack(pady=5)
    
    def new_from_template(self, template_type):
        """从模板新建"""
        self.text_area.delete(1.0, tk.END)
        
        templates = {
            "blank": "",
            "todo": "# 待办清单\n\n- [ ] 任务1\n- [ ] 任务2\n- [ ] 任务3\n",
            "diary": f"# {datetime.now().strftime('%Y年%m月%d日')}\n\n天气：\n心情：\n\n## 今日总结：\n\n",
            "code": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n模块说明\n\"\"\"\n\ndef main():\n    \"\"\"主函数\"\"\"\n    pass\n\nif __name__ == \"__main__\":\n    main()\n"
        }
        
        self.text_area.insert(1.0, templates.get(template_type, ""))
        self.current_file = None
        self.is_modified = True
        self.update_title()
        self.update_status(f"已创建{template_type}模板")
    
    def open_file(self, filepath=None):
        """打开文件"""
        if self.check_save():
            if not filepath:
                file_types = [
                    ("文本文件", "*.txt"),
                    ("Markdown文件", "*.md"),
                    ("HTML文件", "*.html"),
                    ("Python文件", "*.py"),
                    ("所有文件", "*.*")
                ]
                filepath = filedialog.askopenfilename(filetypes=file_types)
            
            if filepath:
                try:
                    with open(filepath, 'r', encoding='utf-8') as file:
                        content = file.read()
                    
                    self.text_area.delete(1.0, tk.END)
                    self.text_area.insert(1.0, content)
                    self.current_file = filepath
                    self.is_modified = False
                    self.update_title()
                    self.add_to_recent(filepath)
                    self.update_status(f"已打开: {os.path.basename(filepath)}")
                    
                except Exception as e:
                    messagebox.showerror("错误", f"无法打开文件:\n{str(e)}")
    
    def save_file(self):
        """保存文件"""
        if self.current_file:
            try:
                content = self.text_area.get(1.0, tk.END)
                with open(self.current_file, 'w', encoding='utf-8') as file:
                    file.write(content)
                
                self.is_modified = False
                self.update_title()
                self.update_status(f"已保存: {os.path.basename(self.current_file)}")
                return True
                
            except Exception as e:
                messagebox.showerror("错误", f"保存失败:\n{str(e)}")
                return False
        else:
            return self.save_as_file()
    
    def save_as_file(self):
        """另存为文件"""
        file_types = [
            ("文本文件", "*.txt"),
            ("Markdown文件", "*.md"),
            ("HTML文件", "*.html"),
            ("Python文件", "*.py"),
            ("所有文件", "*.*")
        ]
        
        filepath = filedialog.asksaveasfilename(
            defaultextension=".txt",
            filetypes=file_types
        )
        
        if filepath:
            try:
                content = self.text_area.get(1.0, tk.END)
                with open(filepath, 'w', encoding='utf-8') as file:
                    file.write(content)
                
                self.current_file = filepath
                self.is_modified = False
                self.update_title()
                self.add_to_recent(filepath)
                self.update_status(f"已另存为: {os.path.basename(filepath)}")
                return True
                
            except Exception as e:
                messagebox.showerror("错误", f"保存失败:\n{str(e)}")
                return False
        return False
    
    def check_save(self):
        """检查是否需要保存"""
        if self.is_modified:
            result = messagebox.askyesnocancel(
                "保存更改",
                "文件已修改，是否保存更改？"
            )
            
            if result is None:  # 取消
                return False
            elif result:  # 是
                return self.save_file()
            else:  # 否
                return True
        return True
    
    def exit_app(self):
        """退出应用"""
        if self.check_save():
            self.root.quit()
    
    def add_to_recent(self, filepath):
        """添加到最近文件列表"""
        if filepath in self.recent_files:
            self.recent_files.remove(filepath)
        self.recent_files.insert(0, filepath)
        self.recent_files = self.recent_files[:self.max_recent]
        self.update_recent_menu()
    
    def update_recent_menu(self):
        """更新最近文件菜单"""
        self.recent_menu.delete(0, tk.END)
        for filepath in self.recent_files:
            if os.path.exists(filepath):
                filename = os.path.basename(filepath)
                self.recent_menu.add_command(
                    label=filename,
                    command=lambda f=filepath: self.open_file(f)
                )
        if not self.recent_files:
            self.recent_menu.add_command(label="无最近文件", state=tk.DISABLED)
    
    def undo(self):
        """撤销操作"""
        try:
            self.text_area.edit_undo()
        except tk.TclError:
            pass  # 没有可撤销的操作
    
    def redo(self):
        """重做操作"""
        try:
            self.text_area.edit_redo()
        except tk.TclError:
            pass  # 没有可重做的操作
    
    def cut(self):
        """剪切文本"""
        if self.text_area.tag_ranges("sel"):
            # 获取选中的文本
            selected_text = self.text_area.get("sel.first", "sel.last")
            # 添加到剪贴板历史
            self.add_to_clipboard_history(selected_text)
            # 执行剪切
            self.text_area.event_generate("<<Cut>>")
    
    def copy(self):
        """复制文本"""
        if self.text_area.tag_ranges("sel"):
            # 获取选中的文本
            selected_text = self.text_area.get("sel.first", "sel.last")
            # 添加到剪贴板历史
            self.add_to_clipboard_history(selected_text)
            # 执行复制
            self.text_area.event_generate("<<Copy>>")
    
    def paste(self):
        """粘贴文本"""
        self.text_area.event_generate("<<Paste>>")
    
    def add_to_clipboard_history(self, text):
        """添加到剪贴板历史"""
        if text in self.clipboard_history:
            self.clipboard_history.remove(text)
        self.clipboard_history.insert(0, text)
        self.clipboard_history = self.clipboard_history[:self.max_clipboard_history]
    
    def show_clipboard_history(self):
        """显示剪贴板历史"""
        if not self.clipboard_history:
            messagebox.showinfo("剪贴板历史", "剪贴板历史为空")
            return
        
        # 创建剪贴板历史对话框
        history_dialog = tk.Toplevel(self.root)
        history_dialog.title("剪贴板历史")
        history_dialog.geometry("400x300")
        history_dialog.transient(self.root)
        history_dialog.grab_set()
        
        # 居中对话框
        history_dialog.update_idletasks()
        x = self.root.winfo_x() + (self.root.winfo_width() - history_dialog.winfo_width()) // 2
        y = self.root.winfo_y() + (self.root.winfo_height() - history_dialog.winfo_height()) // 2
        history_dialog.geometry(f"+{x}+{y}")
        
        # 创建列表框显示历史
        listbox = tk.Listbox(history_dialog)
        listbox.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        # 添加历史项
        for i, text in enumerate(self.clipboard_history):
            # 显示前50个字符
            display_text = text[:50] + "..." if len(text) > 50 else text
            listbox.insert(tk.END, f"{i+1}. {display_text}")
        
        # 粘贴按钮
        def paste_selected():
            selection = listbox.curselection()
            if selection:
                index = selection[0]
                text_to_paste = self.clipboard_history[index]
                self.text_area.insert(tk.INSERT, text_to_paste)
            history_dialog.destroy()
        
        paste_btn = tk.Button(history_dialog, text="粘贴选中项", command=paste_selected)
        paste_btn.pack(pady=5)
        
        # 关闭按钮
        close_btn = tk.Button(history_dialog, text="关闭", command=history_dialog.destroy)
        close_btn.pack(pady=5)
    
    def select_all(self):
        """全选文本"""
        self.text_area.tag_add("sel", "1.0", tk.END)
    
    def toggle_column_select(self):
        """切换列选模式"""
        self.column_select_mode = not self.column_select_mode
        if self.column_select_mode:
            self.update_status("列选模式已启用")
            self.text_area.config(blockcursor=True)  # 显示块状光标
        else:
            self.update_status("列选模式已禁用")
            self.text_area.config(blockcursor=False)  # 恢复默认光标
    
    def show_find_dialog(self):
        """显示查找对话框"""
        if self.find_dialog and self.find_dialog.winfo_exists():
            self.find_dialog.lift()
            return
        
        self.find_dialog = tk.Toplevel(self.root)
        self.find_dialog.title("查找")
        self.find_dialog.geometry("300x150")
        self.find_dialog.transient(self.root)
        
        # 居中对话框
        self.find_dialog.update_idletasks()
        x = self.root.winfo_x() + (self.root.winfo_width() - self.find_dialog.winfo_width()) // 2
        y = self.root.winfo_y() + (self.root.winfo_height() - self.find_dialog.winfo_height()) // 2
        self.find_dialog.geometry(f"+{x}+{y}")
        
        # 查找关键词
        tk.Label(self.find_dialog, text="查找:").pack(pady=5)
        find_entry = tk.Entry(self.find_dialog, width=30)
        find_entry.pack(pady=5)
        find_entry.focus_set()
        
        # 选项框架
        options_frame = tk.Frame(self.find_dialog)
        options_frame.pack(pady=5)
        
        # 匹配大小写
        case_sensitive = tk.BooleanVar()
        case_check = tk.Checkbutton(options_frame, text="匹配大小写", variable=case_sensitive)
        case_check.pack(side=tk.LEFT, padx=5)
        
        # 查找按钮
        def find_text():
            self.find_text(find_entry.get(), case_sensitive.get())
        
        find_btn = tk.Button(self.find_dialog, text="查找下一个", command=find_text)
        find_btn.pack(pady=5)
        
        # 关闭对话框时的清理
        def on_close():
            self.find_dialog = None
            self.find_dialog.destroy()
        
        self.find_dialog.protocol("WM_DELETE_WINDOW", on_close)
    
    def find_text(self, pattern, case_sensitive=False):
        """查找文本"""
        if not pattern:
            return
        
        # 获取当前光标位置
        current_pos = self.text_area.index(tk.INSERT)
        
        # 从当前位置开始搜索
        start_pos = current_pos
        
        # 获取所有文本
        content = self.text_area.get(1.0, tk.END)
        
        # 设置搜索标志
        flags = 0 if case_sensitive else re.IGNORECASE
        
        # 使用正则表达式查找
        match = re.search(pattern, content[start_pos:], flags)
        
        if match:
            # 计算匹配的起始和结束位置
            start = f"1.0 + {start_pos} chars + {match.start()} chars"
            end = f"1.0 + {start_pos} chars + {match.end()} chars"
            
            # 选择匹配的文本
            self.text_area.tag_remove("sel", 1.0, tk.END)
            self.text_area.tag_add("sel", start, end)
            self.text_area.mark_set(tk.INSERT, end)
            self.text_area.see(start)
        else:
            # 如果没有找到，从开头开始搜索
            match = re.search(pattern, content, flags)
            if match:
                # 计算匹配的起始和结束位置
                start = f"1.0 + {match.start()} chars"
                end = f"1.0 + {match.end()} chars"
                
                # 选择匹配的文本
                self.text_area.tag_remove("sel", 1.0, tk.END)
                self.text_area.tag_add("sel", start, end)
                self.text_area.mark_set(tk.INSERT, end)
                self.text_area.see(start)
            else:
                messagebox.showinfo("查找", f"未找到 '{pattern}'")
    
    def show_replace_dialog(self):
        """显示替换对话框"""
        if self.replace_dialog and self.replace_dialog.winfo_exists():
            self.replace_dialog.lift()
            return
        
        self.replace_dialog = tk.Toplevel(self.root)
        self.replace_dialog.title("查找和替换")
        self.replace_dialog.geometry("300x200")
        self.replace_dialog.transient(self.root)
        
        # 居中对话框
        self.replace_dialog.update_idletasks()
        x = self.root.winfo_x() + (self.root.winfo_width() - self.replace_dialog.winfo_width()) // 2
        y = self.root.winfo_y() + (self.root.winfo_height() - self.replace_dialog.winfo_height()) // 2
        self.replace_dialog.geometry(f"+{x}+{y}")
        
        # 查找关键词
        tk.Label(self.replace_dialog, text="查找:").pack(pady=5)
        find_entry = tk.Entry(self.replace_dialog, width=30)
        find_entry.pack(pady=5)
        
        # 替换为
        tk.Label(self.replace_dialog, text="替换为:").pack(pady=5)
        replace_entry = tk.Entry(self.replace_dialog, width=30)
        replace_entry.pack(pady=5)
        
        # 选项框架
        options_frame = tk.Frame(self.replace_dialog)
        options_frame.pack(pady=5)
        
        # 匹配大小写
        case_sensitive = tk.BooleanVar()
        case_check = tk.Checkbutton(options_frame, text="匹配大小写", variable=case_sensitive)
        case_check.pack(side=tk.LEFT, padx=5)
        
        # 按钮框架
        button_frame = tk.Frame(self.replace_dialog)
        button_frame.pack(pady=5)
        
        # 查找按钮
        def find_text():
            self.find_text(find_entry.get(), case_sensitive.get())
        
        find_btn = tk.Button(button_frame, text="查找", command=find_text)
        find_btn.pack(side=tk.LEFT, padx=5)
        
        # 替换按钮
        def replace_text():
            if self.text_area.tag_ranges("sel"):
                # 获取选中的文本
                selected_text = self.text_area.get("sel.first", "sel.last")
                # 检查是否匹配查找文本
                pattern = find_entry.get()
                flags = 0 if case_sensitive else re.IGNORECASE
                if re.fullmatch(pattern, selected_text, flags):
                    # 替换文本
                    self.text_area.delete("sel.first", "sel.last")
                    self.text_area.insert("sel.first", replace_entry.get())
            
            # 查找下一个
            find_text()
        
        replace_btn = tk.Button(button_frame, text="替换", command=replace_text)
        replace_btn.pack(side=tk.LEFT, padx=5)
        
        # 全部替换按钮
        def replace_all():
            # 获取所有文本
            content = self.text_area.get(1.0, tk.END)
            pattern = find_entry.get()
            replacement = replace_entry.get()
            flags = 0 if case_sensitive else re.IGNORECASE
            
            # 执行替换
            new_content = re.sub(pattern, replacement, content, flags=flags)
            
            # 更新文本区域
            self.text_area.delete(1.0, tk.END)
            self.text_area.insert(1.0, new_content)
            
            messagebox.showinfo("替换", f"已完成 {len(re.findall(pattern, content, flags))} 处替换")
        
        replace_all_btn = tk.Button(button_frame, text="全部替换", command=replace_all)
        replace_all_btn.pack(side=tk.LEFT, padx=5)
        
        # 关闭对话框时的清理
        def on_close():
            self.replace_dialog = None
            self.replace_dialog.destroy()
        
        self.replace_dialog.protocol("WM_DELETE_WINDOW", on_close)
    
    def apply_format(self, format_type):
        """应用文本格式"""
        if not self.text_area.tag_ranges("sel"):
            return  # 没有选中的文本
        
        # 获取当前字体配置
        current_font = self.text_area.cget("font")
        font_family = "Consolas"
        font_size = 12
        font_weight = "normal"
        font_slant = "roman"
        font_underline = False
        font_overstrike = False
        
        # 解析当前字体
        if isinstance(current_font, str):
            # 字符串格式的字体，如 "Consolas 12"
            parts = current_font.split()
            if parts:
                font_family = parts[0]
                if len(parts) > 1 and parts[1].isdigit():
                    font_size = int(parts[1])
        elif isinstance(current_font, tuple):
            # 元组格式的字体
            if len(current_font) > 0:
                font_family = current_font[0]
            if len(current_font) > 1:
                font_size = current_font[1]
        
        # 应用格式
        if format_type == "bold":
            font_weight = "bold" if font_weight == "normal" else "normal"
        elif format_type == "italic":
            font_slant = "italic" if font_slant == "roman" else "roman"
        elif format_type == "underline":
            font_underline = not font_underline
        elif format_type == "strike":
            font_overstrike = not font_overstrike
        
        # 创建新字体
        new_font = (font_family, font_size, font_weight, font_slant)
        
        # 应用字体到选中文本
        self.text_area.tag_configure("custom_font", font=new_font, underline=font_underline, overstrike=font_overstrike)
        self.text_area.tag_add("custom_font", "sel.first", "sel.last")
    
    def choose_font(self):
        """选择字体"""
        # 创建字体选择对话框
        font_dialog = tk.Toplevel(self.root)
        font_dialog.title("选择字体")
        font_dialog.geometry("300x200")
        font_dialog.transient(self.root)
        font_dialog.grab_set()
        
        # 居中对话框
        font_dialog.update_idletasks()
        x = self.root.winfo_x() + (self.root.winfo_width() - font_dialog.winfo_width()) // 2
        y = self.root.winfo_y() + (self.root.winfo_height() - font_dialog.winfo_height()) // 2
        font_dialog.geometry(f"+{x}+{y}")
        
        # 字体家族
        tk.Label(font_dialog, text="字体:").pack(pady=5)
        font_family = tk.StringVar(value="Consolas")
        font_list = tk.Listbox(font_dialog, height=4)
        font_list.pack(pady=5, fill=tk.X, padx=10)
        
        # 添加一些常用字体
        common_fonts = ["Consolas", "Courier New", "Arial", "Times New Roman", "Verdana", "Georgia"]
        for font in common_fonts:
            font_list.insert(tk.END, font)
        
        # 字体大小
        tk.Label(font_dialog, text="大小:").pack(pady=5)
        font_size = tk.StringVar(value="12")
        size_spinbox = tk.Spinbox(font_dialog, from_=8, to=72, textvariable=font_size, width=5)
        size_spinbox.pack(pady=5)
        
        # 应用按钮
        def apply_font():
            selected_font = font_list.get(font_list.curselection()) if font_list.curselection() else "Consolas"
            size = int(font_size.get())
            
            # 应用字体到选中文本或所有文本
            if self.text_area.tag_ranges("sel"):
                self.text_area.tag_configure("custom_font", font=(selected_font, size))
                self.text_area.tag_add("custom_font", "sel.first", "sel.last")
            else:
                self.text_area.config(font=(selected_font, size))
            
            font_dialog.destroy()
        
        apply_btn = tk.Button(font_dialog, text="应用", command=apply_font)
        apply_btn.pack(pady=10)
    
    def choose_color(self):
        """选择颜色"""
        color = colorchooser.askcolor(title="选择颜色")
        if color[1]:  # 用户选择了颜色
            # 应用颜色到选中文本
            if self.text_area.tag_ranges("sel"):
                self.text_area.tag_configure("custom_color", foreground=color[1])
                self.text_area.tag_add("custom_color", "sel.first", "sel.last")
            else:
                self.text_area.config(foreground=color[1])

# 启动应用
if __name__ == "__main__":
    root = tk.Tk()
    app = EnhancedNotepad(root)
    root.mainloop()